package examlab.thread;


public class AccountTester extends Thread {

    public static void main(String[] args) throws Exception {
        Account acc = new Account();
        Withdrawer w1 = new Withdrawer();
        w1.acc = acc;
        w1.start();
        //        System.out.println(w1.acc.balance);

        for (int i = 0; i < 100; i++) {
            Withdrawer w2 = new Withdrawer();
            w2.acc = acc;
            w2.start();

        }

    }

}

class Account {

    int balance = 390;

    public void withdraw(int amount) {
        synchronized (this) {

            int diff = balance - amount;

            if (diff > 0) {
                balance -= amount;
            }
        }
        System.out.println(balance);
    }
}

class Withdrawer extends Thread {

    Account acc;

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            acc.withdraw(100);
        }
    }
}

class Test extends Thread {

    Object obj1 = new Object();
    Object obj2 = new Object();
    int t;

    Test(int t) {
        this.t = t;
    }

    public void m1() {
        synchronized (obj1) {
            System.out.println("Entrei no M1 sync OBJ1: " + t);
            synchronized (obj2) {
                System.out.println("Entrei no M1 sync OBJ2: " + t);
            }
        }
    }

    public void m2() {
        synchronized (obj2) {
            System.out.println("Entrei no M2 sync OBJ2: " + t);
            synchronized (obj1) {
                System.out.println("Entrei no M2 sync OBJ1: " + t);
            }
        }
    }

    @Override
    public void run() {
        if (t == 1) {
            m1();
        } else {
            m2();
        }
    }

    public static void main(String[] args) {
        new Test(1).start();
        new Test(2).start();
        new Test(3).start();
        new Test(4).start();
    }
}
